/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.common.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.DataEntity;

/**
 * Service基类
 * 
 * @author ThinkGem
 * @version 2014-05-16
 */
@Transactional(readOnly = false)
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity> extends BaseService {

	/**
	 * 持久层对象
	 */
	@Autowired
	protected D dao;

	/**
	 * 获取单条数据
	 * 
	 * @param entity
	 * @return
	 */
	public T get(T entity) {
		return dao.get(entity);
	}

	/**
	 * 查询列表数据
	 * 
	 * @param entity
	 * @return
	 */
	public List<T> findList(T entity) {
		return dao.findList(entity);
	}

	public List<T> findAll() {
		return dao.findAll();
	}

	/**
	 * 查询分页数据
	 * 
	 * @param page
	 *            分页对象
	 * @param entity
	 * @return
	 */
	public PageInfo<T> findPage(Integer pageNo, Integer pageSize, T entity) {
		// entity.setPage(page);
		// page.setList(dao.findList(entity));
		// return page;
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 30 : pageSize;
		PageHelper.startPage(pageNo, pageSize);
		// entity.setPage(new
		// com.thinkgem.jeesite.common.persistence.Page<T>(pageNo,pageSize));
		return new PageInfo<>(dao.findList(entity));
	}

	/**
	 * 保存数据（插入或更新）
	 * 
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void save(T entity) {
		entity.preInsert();
		dao.insert(entity);
	}

	@Transactional(readOnly = false)
	public int update(T entity) {
		entity.preInsert();
		return dao.update(entity);
	}

	@Transactional(readOnly = false)
	public void saveOrUpdate(T entity) {
		dao.insertOrUpdate(entity);
	}

	/**
	 * 删除数据
	 * 
	 * @param entity
	 */
	@Transactional(readOnly = false)
	public void delete(T entity) {
		dao.delete(entity);
	}

}
